package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.search.vos.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * ES监听kafka消息进行消费
 */
@Slf4j
@Component
public class SyncArticleListener {
    @Autowired
    private RestHighLevelClient client;

    /**
     * 同步app端新增的文章
     * @param message
     */
    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void onMessage(String message) {
        if (StringUtils.isNotEmpty(message)) {
            log.info("search监听到文章数据,开始更新es索引库....");
            SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);

            //更新es索引文档
            //1.创建request对象
            IndexRequest request = new IndexRequest("app_info_article").id(searchArticleVo.getId().toString());
            //2.构建DSL
            request.source(message, XContentType.JSON);
            try {
                //3.发送请求
                client.index(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
                log.info("es文章索引库更新失败....");
            }

        }
    }


    //监听自媒体端文章上架 下架时,对ES数据进行同步(删除索引 或者 新增索引)
}
